package controller

import (
	"errors"
	"fmt"
	"github.com/chenhg5/collection"
	"github.com/disintegration/imaging"
	"github.com/satori/go.uuid"
	"io"
	"io/ioutil"
	"net/http"
	"os"
	"path"
	"picupload/config"
	"picupload/model"
	"picupload/util"
	"strings"
	"time"
)

//此方法不用了
func UploadFileHandler(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "text/html;charset=utf-8")
	r.ParseForm()
	if r.Method != "POST" {
		w.Write([]byte(html))
	} else {
		uploadFile, handle, err := r.FormFile("file")
		errorHandle(err, w)
		ext := strings.ToLower(path.Ext(handle.Filename))
		allow_ext := []string{".jpg", ".jpeg", ".png", ".ico", ".xls", ".xlsx"}
		has := collection.Collect(allow_ext).Contains(ext) //go get github.com/chenhg5/collection
		if has == false {
			errorHandle(errors.New("不支持的格式"), w)
			return
		}
		isdir, _ := util.PathExists(config.UPLOAD_PATH)
		if isdir == true {
			os.MkdirAll(config.UPLOAD_PATH, 0777)
		}
		saveFile, err := os.OpenFile(config.UPLOAD_PATH+handle.Filename, os.O_WRONLY|os.O_CREATE, 0666)
		errorHandle(err, w)
		io.Copy(saveFile, uploadFile)
		defer uploadFile.Close()
		defer saveFile.Close()
		w.Write([]byte("查看上传图片: <a target='_blank' href='/" + config.UPLOAD_PATH + handle.Filename + "'>" + handle.Filename + "</a>"))
	}
}

// 统一错误输出接口
func errorHandle(err error, w http.ResponseWriter) {
	if err != nil {
		w.Write([]byte(err.Error()))
	}
}

const html = `<html>
    <head><meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"></head>
    <body>
        <form method="post" enctype="multipart/form-data">
            <input type="file" name="file" />
            <input type="submit" />
        </form>
    </body>
</html>`

func UploadHandler(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "text/html;charset=utf-8")
	r.ParseForm()
	if r.Method == "GET" {
		io.WriteString(w, "<html><head><title>上传</title></head>"+
			"<body><form action='#' method=\"post\" enctype=\"multipart/form-data\">"+
			"<label>上传图片</label>"+":"+
			"<input type=\"file\" name='file'  /><br/><br/>    "+
			"<label><input type=\"submit\" value=\"上传图片\"/></label></form></body></html>")
	} else {
		file, head, err := r.FormFile("file")
		if err != nil {
			fmt.Println(err)
			return
		}
		defer file.Close()
		isdir, _ := util.PathExists(config.UPLOAD_PATH)
		if isdir == true {
			os.MkdirAll(config.UPLOAD_PATH, 0777)
		}

		ext := strings.ToLower(path.Ext(head.Filename))
		allow_ext := []string{".jpg", ".jpeg", ".png", ".ico", ".xls", ".xlsx"}
		allow_pic := []string{".jpg", ".jpeg", ".png"}
		has := collection.Collect(allow_ext).Contains(ext) //go get github.com/chenhg5/collection
		if has == false {
			errorHandle(errors.New("不支持的格式"), w)
			return
		}

		uid := uuid.Must(uuid.NewV4()).String()
		uid = strings.Replace(uid, "-", "", -1)
		newFilePath := config.UPLOAD_PATH + uid + ext
		errorHandle(err, w)

		fw, err := os.OpenFile(newFilePath, os.O_WRONLY|os.O_CREATE, 0666)
		//fw, err := os.Create(config.UPLOAD_PATH + head.Filename)
		errorHandle(err, w)
		defer fw.Close()
		_, err = io.Copy(fw, file)
		errorHandle(err, w)

		md5 := util.GetMd5ByPath(newFilePath)
		hasFile, num := model.GetByFilehash(md5)
		if num > 0 {
			//todo 文件存在，删除临时文件
			w.Write([]byte(head.Filename + "文件已存在,文件地址: <a target='_blank' href='" + hasFile.Fileurl + "'>" + head.Filename + "</a>"))
			return
		}

		thumbPath := ""
		if collection.Collect(allow_pic).Contains(ext) == true { //config.UPLOAD_PATH+uid+"_thumb"+ext
			img, _ := imaging.Open(newFilePath)
			/**
			imaging包
			go get -u golang.org/x/image 无法下载 需自行下载https://github.com/golang/image后放入src相应地址
			go get -u github.com/disintegration/imaging
			*/
			thumbPath = config.UPLOAD_PATH + uid + "_thumb" + ext
			dst := imaging.Resize(img, 100, 0, imaging.Lanczos)
			imaging.Save(dst, thumbPath)
		}

		var filedata model.Filedata
		filedata.Userid = 100
		filedata.Filename = head.Filename
		filedata.Fileurl = config.URL + "/" + newFilePath
		filedata.Filehash = md5
		filedata.Filethumb = config.URL + "/" + thumbPath
		filedata.Size = int(head.Size) / 1024
		filedata.Source = 1
		filedata.CreatedAt = time.Now()
		filedata.UpdatedAt = time.Now()
		rows := model.AddFiledata(filedata)
		fmt.Println(rows)

		w.Write([]byte("查看上传图片: <a target='_blank' href='/" + newFilePath + "'>" + head.Filename + "</a>"))
	}
}

//显示文件接口
func ShowFileHandler(w http.ResponseWriter, r *http.Request) {
	fmt.Println(r.URL.Path)
	file, err := os.Open("." + r.URL.Path)
	if err != nil {
		fmt.Println(err)
	}
	defer file.Close()
	buff, err := ioutil.ReadAll(file)
	if err != nil {
		fmt.Println(err)
	}
	w.Write(buff)
}
